package com.beemans.common.ext

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.annotation.ArrayRes
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.Utils

/**
 * @author tiamosu
 * @date 2021/3/12
 */

/**
 * 通过资源 ID 生成 Bitmap，可重新指定大小
 */
fun @receiver:DrawableRes Int.toBitmap(
    newWidth: Int = 0,
    newHeight: Int = 0
): Bitmap? {
    val bitmap: Bitmap? = ImageUtils.getBitmap(this)
    if (newWidth == 0 || newHeight == 0) {
        return bitmap
    }
    return ImageUtils.scale(bitmap, newWidth, newHeight)
}

/**
 * 通过资源 ID 获取 Drawable
 */
fun @receiver: DrawableRes Int.toDrawable(): Drawable? {
    return ContextCompat.getDrawable(Utils.getApp(), this)
}

/**
 * 通过资源 ID 获取颜色
 */
fun @receiver:ColorRes Int.toColor(): Int {
    return ContextCompat.getColor(Utils.getApp(), this)
}

/**
 * 通过资源 ID 获取字符串数组
 */
fun @receiver:ArrayRes Int.toStringArray(): Array<out String> {
    return Utils.getApp().resources.getStringArray(this)
}

/**
 * 通过资源 ID 获取字符串
 */
fun @receiver:StringRes Int.toString2(
    context: Context? = null,
    vararg formatArgs: Any
): String {
    val newContext = context ?: Utils.getApp()
    return if (formatArgs.isNotEmpty()) {
        newContext.getString(this, *formatArgs)
    } else {
        newContext.getString(this)
    }
}